﻿using System.Data.Entity;
using System.Data.Objects.SqlClient;
using System.Linq;
using Pyramid.Models;

namespace Pyramid.Bll
{
	public class StaffHelper : BllBase
	{
		public static StaffHelper NewInstance
		{
			get { return new StaffHelper(); }
		}

		#region query

		/// <summary>
		/// 获取查询员工的查询语句
		/// </summary>
		public IQueryable<Staff> GetStaves(StaffQueryModel model)
		{
			var staves = Db.Staves.Include(x => x.Department).Include(x => x.Position).AsQueryable();
			if (!string.IsNullOrWhiteSpace(model.StaffCode))
			{
				staves = staves.Where(x => x.Code.Contains(model.StaffCode));
			}
			if (!string.IsNullOrWhiteSpace(model.Keywords))
			{
				staves = staves.Where(x => x.FullName.Contains(model.Keywords));
			}
			if (model.DepartmentId.HasValue)
			{
				staves = staves.Where(x => x.DepartmentId == model.DepartmentId);
			}
			if (model.PositionId.HasValue)
			{
				staves = staves.Where(x => x.PositionId == model.PositionId.Value);
			}
			if (model.EntryDateFrom.HasValue)
			{
				staves = staves.Where(x => SqlFunctions.DateDiff("d", model.EntryDateFrom.Value, x.EntryDate) >= 0);
			}
			if (model.EntryDateTo.HasValue)
			{
				staves = staves.Where(x => SqlFunctions.DateDiff("d", model.EntryDateTo.Value, x.EntryDate) <= 0);
			}
			return staves;
		}

		public IQueryable<Staff> GetStaves(StaffMonthlyQueryModel model)
		{
			var staves = Db.Staves.Include(x => x.Department).Include(x => x.Position).AsQueryable();
			if (!string.IsNullOrWhiteSpace(model.Keywords))
			{
				staves = staves.Where(x => x.FullName.Contains(model.Keywords) || x.Code.Contains(model.Keywords));
			}
			if (model.DepartmentId.HasValue)
			{
				staves = staves.Where(x => x.DepartmentId == model.DepartmentId);
			}
			if (model.PositionId.HasValue)
			{
				staves = staves.Where(x => x.PositionId == model.PositionId.Value);
			}
			return staves;
		}

		public Staff GetStaff(int staffId)
		{
			return Db.Staves.Single(x => x.Id == staffId);
		}

		#endregion

		#region data prepare

		public void UpdateAccountModel(int staffId, Account model)
		{
			var staff = GetStaff(staffId);
			model.ExtInfoId = staffId;
			model.ExtInfoName = staff.FullName;
			model.UserType = (int) UserTypes.Staff;
		}

		#endregion

		#region insert or update

		#endregion
	}
}